import styled from "@emotion/styled"
import { Link, NavLink } from "react-router-dom"
import ProgressBar from "./ProgressBar"
import { progressAtom, UserInfoAtom, vipLevelAtom, vipNextAtom, isCopiedAtom } from "../atom"
import { useAtom } from "jotai"
import { useEffect, useCallback } from "react"
import { Repository } from "@/atoms/api_repositories"
import ProgressDot from "./ProgressDot"
import { resolveAssetImage } from "@/utils/common"
import { SvgComponent } from "@/components/base/Svg"

const UserCenterTop = styled.div`
    position: relative;
    display: flex;
    flex-direction: column;
    background: rgba(163, 223, 250, 0.1);
    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 300rem;
        background: linear-gradient(129deg, #ffbce4, #f9e5b3, #b2dadf, #a9c7dc);
        backdrop-filter: blur(10px);
        z-index: 0;
    }
    &::after {
        content: "";
        position: absolute;
        width: 100%;
        height: 300rem;
        background: linear-gradient(180deg, rgba(240, 241, 245, 0) 0%, #f0f1f5 25%);
        top: 114rem;
        z-index: 1;
    }
    background-attachment: fixed;
`
const TopContainer = styled.div`
    z-index: 1;
    position: relative;
    display: flex;
    flex-direction: column;
    width: 375rem;
    height: 108rem;
`
const TopRightIcons = styled(NavLink)`
    /* display: flex;
    flex-direction: row;
    justify-content: flex-end; */
    /* position: sticky;
    top: 0;
    right: 0; */
    /* padding: 8rem 16rem; */
    /* align-items: center; */
    width: 100%;
    height: 100%;
`
const MailIcon = styled(SvgComponent("pages/UserCenterPage/mail1.svg"))`
    width: 28rem;
    height: 28rem;
    margin-right: 18rem;
`
const ServiceIcon = styled(SvgComponent("pages/UserCenterPage/service.svg"))`
    width: 28rem;
    height: 28rem;
    display: block;
    position: absolute;
    top: 8rem;
    right: 16rem;
`

const AvatarLine = styled.div`
    width: 375rem;
    display: flex;
    align-items: center;
    /* margin: 0 auto 8rem; */
    height: 56rem;
`
const AvatarContainer = styled.div`
    width: 68rem;
    height: 68rem;
    position: relative;
    margin-left: 24rem;
    display: flex;
    align-items: center;
    justify-content: center;
`
const AvatarIcon = styled.img`
    width: 48rem;
    height: 48rem;
`

const AvatarCenter = styled.div`
    margin-left: 6rem;
    /* margin-right: 27rem; */
    width: 147rem;
`

const AvatarCTop = styled.div`
    color: #131416;
    font-weight: 700;
    font-size: 20rem;
    height: 28rem;
    text-transform: capitalize;
`
const AvatarCBottom = styled.div`
    display: flex;
    align-items: center;
    font-weight: 500;
    height: 20rem;
    color: #69728c;
    position: relative;
`

const IdText = styled.div`
    margin-right: 4rem;
`
const IdVal = styled.div`
    margin-right: 8rem;
    width: 71rem;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
`
const CopyIcon = styled(SvgComponent("pages/UserCenterPage/copy.svg"))`
    width: 20rem;
    height: 20rem;
`

const CopyTooltip = styled.div`
    position: absolute;
    top: -30rem;
    left: 65%;
    transform: translateX(-50%);
    background: #333;
    color: #fff;
    font-size: 12rem;
    padding: 4rem 8rem;
    border-radius: 4rem;
    white-space: nowrap;
    z-index: 10;
`

const AccountCenter = styled(Link)`
    text-decoration: none;
    background: rgba(255, 255, 255, 0.6);
    border-radius: 20rem;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #40444f;
    font-size: 12rem;
    font-weight: 500;
    width: 120rem;
    height: 24rem;
    line-height: 24rem;
`
const AccountText = styled.div`
    width: 87rem;
    margin-left: 10rem;
`
const RightArrow = styled(SvgComponent("pages/UserCenterPage/right_arrow.svg"))`
    width: 4.93rem;
    height: 9.33rem;
    margin-left: 5.73rem;
    margin-right: 12.33rem;
`

const VipCenter = styled.div`
    width: 335rem;
    height: 84rem;
    padding-top: 4rem;
    position: relative;
    display: flex;
    justify-content: center;
    margin: 0 auto;
`

const VipCLeft = styled.div`
    width: 335rem;
    height: 80rem;
    position: relative;
    & > img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }
    & > div {
        position: relative;
    }
`
const VipCRight = styled.div`
    width: 135rem;
    height: 50rem;
    display: flex;
    border-top-right-radius: 8rem;
    padding-top: 9rem;
    padding-left: 45rem;
    color: #ffffff;
    position: absolute;
    right: 0;
    top: 4rem;
    z-index: -1;
    & > img {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 0;
    }
    & > span {
        position: relative;
    }
`
const VipNumText = styled.div`
    width: 194rem;
    height: 24rem;
    font-size: 18rem;
    font-weight: 700;
    margin-top: 12rem;
    margin-left: 12rem;
    margin-bottom: 12rem;
    color: #7d451c;
`
const VipTipText = styled.div`
    width: 311rem;
    height: 12rem;
    line-height: 12rem;
    font-size: 10rem;
    font-weight: 500;
    margin-left: 12rem;
    color: #7d451c;
`

const VipLBottom = styled.div`
    display: flex;
    align-items: baseline;
    position: relative;
`

const VipBottomText = styled.div`
    font-family: "Gilroy";
    font-weight: 700;
    font-size: 14rem;
    margin-left: 6rem;
    color: #7d451c;
`
const VipBase = styled(SvgComponent("pages/UserCenterPage/vip_base.svg"))`
    width: 375rem;
    height: 125rem;
    z-index: -1;
    position: absolute;
    top: 176rem;
    left: 0;
`
const BaseCover = styled.div`
    width: 375rem;
    height: 12rem;
    z-index: -2;
    position: absolute;
    top: 195rem;
    left: 0;
    background-color: #f0f1f5;
`
const CrownContainer = styled.div`
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
    animation: crownAnimation 1s infinite;

    @keyframes crownAnimation {
        0% {
            transform: rotate(0deg);
        }
        50% {
            transform: rotate(10deg);
        }
        100% {
            transform: rotate(0deg);
        }
    }
`
const CorwnText = styled.div`
    font-family: "Gilroy";
    font-weight: 700;
    font-size: 8rem;
    position: absolute;
    top: 47rem;
    left: 25rem;
    text-align: center;
`
const AvatarCrown = styled(SvgComponent("pages/UserCenterPage/avatar_frame_bronze.svg"))`
    width: 68rem;
    height: 68rem;
`
const DotContainer = styled.div`
    position: absolute;
    height: 4rem;
    left: 12rem;
    width: 272rem;
    top: 9rem;
`
const VipCleftSvg = styled(SvgComponent("pages/UserCenterPage/vip_c_left.svg"))`
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
`
const VipCRightSvg = styled(SvgComponent("pages/UserCenterPage/vip_c_right1.svg"))`
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 0;
`
export default function RootLayout() {
    const { data: profile, fetch: fetchUserInfo, loading } = Repository.useRefGetProfile()
    //状态管理
    const [userInfo, setUserInfo] = useAtom(UserInfoAtom)
    const [vipLevel] = useAtom(vipLevelAtom)
    const [vipNext] = useAtom(vipNextAtom)
    const [progress, setProgress] = useAtom(progressAtom)
    const [isCopied, setIsCopied] = useAtom(isCopiedAtom)
    // 复制功能
    const handleCopy = useCallback(async () => {
        const textToCopy = userInfo?.uid
        if (!textToCopy) {
            console.error("Username is undefined, cannot copy to clipboard.")
            return
        }

        const fallbackCopy = (text: string) => {
            const textarea = document.createElement("textarea")
            textarea.value = text
            textarea.style.position = "fixed" // 防止页面跳动
            document.body.appendChild(textarea)
            textarea.focus()
            textarea.select()

            try {
                // @ts-ignore
                const successful = document.execCommand("copy")
                if (!successful) throw new Error("Fallback copy failed")
                console.log("Copied with fallback method!")
            } catch (err) {
                console.error("Fallback: Unable to copy", err)
            }

            document.body.removeChild(textarea)
        }

        try {
            if (navigator?.clipboard?.writeText) {
                await navigator.clipboard.writeText(textToCopy)
                console.log("Copied using Clipboard API!")
            } else {
                fallbackCopy(textToCopy)
            }
            setIsCopied(true)
            setTimeout(() => setIsCopied(false), 2000)
        } catch (err) {
            console.error("Failed to copy:", err)
            fallbackCopy(textToCopy) // 尝试降级方案
        }
    }, [userInfo, setIsCopied])

    useEffect(() => {
        if (!profile) {
            fetchUserInfo()
        } else {
            setUserInfo(profile)
        }
    }, [profile, fetchUserInfo, setUserInfo])
    useEffect(() => {
        const interval = setInterval(() => {
            setProgress((progress) => (progress >= 100 ? 0 : progress + 10))
        }, 2000)
        return () => clearInterval(interval)
    }, [setProgress])

    return (
        <>
            <UserCenterTop>
                <TopContainer>
                    <TopRightIcons to={"/my/service"}>
                        {/* <NavLink to={"/my/news"}>
                        <MailIcon></MailIcon>
                    </NavLink> */}
                        {/* <NavLink to={"/my/service"}> */}
                        <ServiceIcon />
                        {/* </NavLink> */}
                    </TopRightIcons>
                    <AvatarLine>
                        <AvatarContainer>
                            <AvatarIcon
                                src={
                                    userInfo?.avatarUrl
                                        ? userInfo?.avatarUrl
                                        : resolveAssetImage(
                                              "pages/UserCenterPage/img_not_found.webp",
                                          )
                                }
                                alt="Avatar Icon"
                            ></AvatarIcon>
                            <CrownContainer>
                                <CorwnText>VIP6</CorwnText>
                                <AvatarCrown></AvatarCrown>
                            </CrownContainer>
                        </AvatarContainer>
                        <AvatarCenter>
                            <AvatarCTop>{userInfo?.nickname}</AvatarCTop>
                            <AvatarCBottom>
                                <IdText>ID:</IdText>
                                <IdVal>{userInfo?.uid}</IdVal>
                                <CopyIcon onClick={handleCopy}></CopyIcon>
                                {isCopied && <CopyTooltip>Copied!</CopyTooltip>}
                            </AvatarCBottom>
                        </AvatarCenter>
                        <AccountCenter to={"/s-account"}>
                            <AccountText>Account Center</AccountText>
                            <RightArrow></RightArrow>
                        </AccountCenter>
                    </AvatarLine>
                </TopContainer>
                {/* <VipCenter>
                    <VipCLeft>
                        <VipCleftSvg />
                        <VipNumText>{vipLevel}</VipNumText>
                        <VipTipText>You need to bet another 200 to upgrade to VIP7</VipTipText>
                        <VipLBottom>
                            <ProgressBar progress={60} /> 
                            <VipBottomText>{vipNext}</VipBottomText>
                            <DotContainer>
                                <ProgressDot
                                    progress={60} // 百分比位置 0-100
                                    size={5.5} // rem
                                    color="#ffffff"
                                    animated={true}
                                ></ProgressDot>
                            </DotContainer>
                        </VipLBottom>
                    </VipCLeft>
                    <VipCRight>
                        <VipCRightSvg />
                        <span>VIP Center →</span>
                    </VipCRight>
                </VipCenter> */}
            </UserCenterTop>
            {/* <VipBase></VipBase>*/}
            {/* <BaseCover></BaseCover> */}
        </>
    )
}
